# -*- coding: UTF-8 -*-
import os
from Tkinter import *
#import Tkinter
from PIL import Image

import win32clipboard  
import win32gui  
import win32api  
import win32con  
import traceback  
  
from PIL import Image
from PIL import ImageTk
from cStringIO import StringIO  

from bs4 import BeautifulSoup
import requests
import re

import json


class SearchImg():
    def __init__(self,_root):
        self.keyword = ''
        self.urls = []
        self.parent = _root
        self.BaiduSearchUrl = 'https://image.baidu.com/search/acjson'
        self.savePath = ''
        
    # 展示搜索栏
    def ShowSearchUi(self):
        e = StringVar()
        entry = Entry(self.parent, textvariable = e)
        e.set('input your text here')
        entry.grid(row=0, column=0, columnspan=1, sticky=W + E + N + S, padx=10, pady=10);
        findbtn = Button(self.parent, text='Search', relief=GROOVE, command =  lambda : self.searchEmotion(entry,e,))
        findbtn.grid(row=0, column=1,columnspan=1, sticky=W + E + N + S, padx=10, pady=10);

    def searchEmotion(self,txtobj,e):
        self.keyword = txtobj.get()
        self.savePath = "./photo/"+self.keyword+'/'
        e.set('')
        dataList = self.getManyPages(self.keyword, 1)
        self.getImg(dataList, self.savePath)

        
    # 参数1:关键字，参数2:要下载的页数
    def getManyPages(self, keyword,pages):
        params=[]
        for i in range(30,30*pages+30,30):
            params.append({
                          'tn': 'resultjson_com',
                          'ipn': 'rj',
                          'ct': 201326592,
                          'is': '',
                          'fp': 'result',
                          'queryWord': keyword,
                          'cl': 2,
                          'lm': -1,
                          'ie': 'utf-8',
                          'oe': 'utf-8',
                          'adpicid': '',
                          'st': -1,
                          'z': '',
                          'ic': 0,
                          'word': keyword,
                          's': '',
                          'se': '',
                          'tab': '',
                          'width': '',
                          'height': '',
                          'face': 0,
                          'istype': 2,
                          'qc': '',
                          'nc': 1,
                          'fr': '',
                          'pn': i,
                          'rn': 30,
                          'gsm': '1e',
                          '1488942260214': ''
                      })
        urls = []
        for i in params:
            replacedQuoteJson = re.sub(r"\\x26([a-zA-Z]{2,6});", r"&\1;", requests.get(self.BaiduSearchUrl, params=i).content);
            urls = urls + re.findall('"thumbURL":"(.*?)"',replacedQuoteJson)
            print urls
        return urls

    # 参数2:指定保存的路径
    def getImg(self, dataList, localPath):
        if not os.path.exists(localPath):  # 新建文件夹
            os.makedirs(localPath)
        x = 0
        for one in dataList:
            print(u'正在下载：%s' % one)
            ir = requests.get(one)
            open(localPath + '%d.jpg' % x, 'wb').write(ir.content)
            x += 1
        self.smallSize(localPath)

    def smallSize(self, localPath):
        if not os.path.exists(localPath):
            print '文件夹错误'
            return
        allfile = os.listdir(localPath)
        for i in range(0,len(allfile)):
            path = os.path.join(localPath,allfile[i])
            print path
            if os.path.isfile(path):
                Imgfile = Image.open(path).convert('RGB')
                size = (Imgfile.size[0]/3,Imgfile.size[1]/3)
                smallImg = Imgfile.resize(size, Image.ANTIALIAS)#改变尺寸  
                smallImg.save(path, 'JPEG', quality = 90)
        
        
class CanvasImg():
    def __init__(self,_path,_root):
        self.imgPath = _path
        self.imgList = os.listdir(self.imgPath)
        self.parent = _root
        
    def addImgd(self):
        _row = 1
        _column = 0
        #for img in self.imgList:
        img = self.imgList[0]
        _imgfile = os.path.join(self.imgPath, img)
        print _imgfile
        if os.path.isfile(_imgfile):
            self.addImgToShow(_imgfile, 1, 0)
            _column += 2
            if _column == 12:
                _row += 1
                _column = 0
                print _row,_column
        
    def addImgToShow(self ,_imgpath , _row, _column):
        imgob = Image.open(_imgpath)
        size = imgob.size
        PhotoImage = ImageTk.PhotoImage(file = _imgpath)
        print PhotoImage
        cv = Canvas(self.parent, bg = 'white', width = size[0], height = size[1])
        #rt = cv.create_rectangle(10,10,110,110,outline='red',stipple='gray12',fill='green')
        cv.create_image((size[0]/2,size[1]/2),image = PhotoImage)
        cv.bind("<B1-Motion>",self.addFunctionClick(imgob))
        cv.grid(row=_row, column=_column, columnspan=1, sticky=W + E + N + S, padx=10, pady=10);
        
    def addFunctionClick(self, _imgob):
        output = StringIO()  
        _imgob.convert("RGB").save(output, "BMP")  
        data = output.getvalue()[14:]  
        output.close()  
        win32clipboard.OpenClipboard()  
        try:  
            # Unicode tests  
            win32clipboard.EmptyClipboard()  
            win32clipboard.SetClipboardData(win32con.CF_DIB, data)  
        except:  
            traceback.print_exc()  
        finally:  
            win32clipboard.CloseClipboard()
    
if __name__ == '__main__':
    root = Tk()
    root.title("司机开车工具")  # 设置窗口标题
    
    UIBtn = SearchImg(root)
    UIBtn.ShowSearchUi()
    
    canvas1 = CanvasImg('./photo/13/',root);
    canvas1.addImgd()
    
    root.mainloop()